#!/bin/bash

# 头条自动发文系统 - 本地部署脚本
# 不依赖GitHub，直接在服务器上部署

set -e

echo "🚀 开始部署头条自动发文系统..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}请使用root用户运行此脚本${NC}"
    exit 1
fi

# 1. 更新系统
echo -e "${BLUE}📦 更新系统包...${NC}"
dnf update -y

# 2. 安装Docker
echo -e "${BLUE}🐳 安装Docker...${NC}"
if ! command -v docker &> /dev/null; then
    dnf install -y dnf-plugins-core
    dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo
    dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    
    systemctl start docker
    systemctl enable docker
    echo -e "${GREEN}✅ Docker安装完成${NC}"
else
    echo -e "${YELLOW}⚠️ Docker已安装${NC}"
fi

# 3. 安装Docker Compose
echo -e "${BLUE}🔧 安装Docker Compose...${NC}"
if ! command -v docker-compose &> /dev/null; then
    curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    echo -e "${GREEN}✅ Docker Compose安装完成${NC}"
else
    echo -e "${YELLOW}⚠️ Docker Compose已安装${NC}"
fi

# 4. 创建项目目录
PROJECT_DIR="/opt/toutiao-auto-publish"
echo -e "${BLUE}📁 创建项目目录: ${PROJECT_DIR}${NC}"
mkdir -p ${PROJECT_DIR}
cd ${PROJECT_DIR}

# 5. 创建Dockerfile
echo -e "${BLUE}📄 创建Dockerfile...${NC}"
cat > Dockerfile << 'EOF'
FROM python:3.11-slim

WORKDIR /app

ENV PYTHONUNBUFFERED=1
ENV DISPLAY=:99
ENV DEBIAN_FRONTEND=noninteractive

# 安装系统依赖和Chrome
RUN apt-get update && apt-get install -y \
    wget curl gnupg2 software-properties-common apt-transport-https ca-certificates \
    fonts-liberation libasound2 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 \
    libcups2 libdbus-1-3 libdrm2 libgtk-3-0 libnspr4 libnss3 libxcomposite1 \
    libxdamage1 libxfixes3 libxkbcommon0 libxrandr2 xdg-utils xvfb \
    fonts-wqy-zenhei fonts-wqy-microhei ttf-wqy-zenhei ttf-wqy-microhei \
    && rm -rf /var/lib/apt/lists/*

# 安装Chrome
RUN wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list \
    && apt-get update \
    && apt-get install -y google-chrome-stable \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

RUN mkdir -p /app/browser_data /app/uploads /app/logs /app/static/uploads
RUN chmod +x /app/run.py

RUN echo '#!/bin/bash\nXvfb :99 -screen 0 1920x1080x24 &\nsleep 2\npython run.py' > /app/start.sh && chmod +x /app/start.sh

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost:8000/ || exit 1

CMD ["/app/start.sh"]
EOF

# 6. 创建docker-compose.yml
echo -e "${BLUE}📄 创建docker-compose.yml...${NC}"
cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
  toutiao-app:
    build: .
    container_name: toutiao-auto-publish
    ports:
      - "8000:8000"
    volumes:
      - ./data:/app/data
      - ./logs:/app/logs
      - ./uploads:/app/uploads
      - ./browser_data:/app/browser_data
      - ./.env:/app/.env:ro
    environment:
      - PYTHONUNBUFFERED=1
      - DISPLAY=:99
      - BROWSER_HEADLESS=true
      - BROWSER_NO_SANDBOX=true
    restart: unless-stopped
    deploy:
      resources:
        limits:
          memory: 2G
          cpus: '1.0'
        reservations:
          memory: 1G
          cpus: '0.5'
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 60s
    security_opt:
      - no-new-privileges:true
    networks:
      - toutiao-network

networks:
  toutiao-network:
    driver: bridge
EOF

# 7. 创建requirements.txt
echo -e "${BLUE}📄 创建requirements.txt...${NC}"
cat > requirements.txt << 'EOF'
# Web框架
fastapi==0.104.1
uvicorn[standard]==0.24.0
jinja2==3.1.2
python-multipart==0.0.6

# 浏览器自动化
DrissionPage==4.0.5.6

# HTTP请求
requests==2.31.0
httpx==0.25.2

# 文件处理
aiofiles==24.1.0
pillow==10.1.0

# 配置管理
python-dotenv==1.0.0
pydantic==2.5.0

# 二维码生成
qrcode[pil]==7.4.2

# 日志处理
loguru==0.7.2

# 数据处理
pandas==2.1.4
numpy==1.25.2

# 时间处理
python-dateutil==2.8.2

# 加密
cryptography==41.0.8

# 系统工具
psutil==5.9.6

# 开发工具
watchdog==3.0.0
EOF

# 8. 创建必要目录
echo -e "${BLUE}📁 创建数据目录...${NC}"
mkdir -p data logs uploads browser_data

# 9. 设置权限
echo -e "${BLUE}🔐 设置目录权限...${NC}"
chmod 755 data logs uploads browser_data
chown -R 1000:1000 data logs uploads browser_data

# 10. 创建环境配置
echo -e "${BLUE}⚙️ 创建环境配置...${NC}"
cat > .env << EOF
# 应用配置
SECRET_KEY=$(openssl rand -hex 32)
DEBUG=False

# 服务器配置
HOST=0.0.0.0
PORT=8000

# 浏览器配置
BROWSER_HEADLESS=true
BROWSER_NO_SANDBOX=true
BROWSER_DISABLE_GPU=true
BROWSER_DISABLE_DEV_SHM=true

# 日志配置
LOG_LEVEL=INFO
LOG_FILE=/app/logs/app.log

# 文件上传配置
UPLOAD_DIR=/app/uploads
MAX_FILE_SIZE=10485760

# 头条配置
TOUTIAO_LOGIN_URL=https://mp.toutiao.com/auth/page/login/
TOUTIAO_PUBLISH_URL=https://mp.toutiao.com/profile_v4/graphic/publish
TOUTIAO_TITLE_URL=https://mp.toutiao.com/profile_v4/graphic/articles
EOF

# 11. 配置防火墙
echo -e "${BLUE}🔥 配置防火墙...${NC}"
if command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-port=8000/tcp
    firewall-cmd --reload
    echo -e "${GREEN}✅ 防火墙配置完成${NC}"
else
    echo -e "${YELLOW}⚠️ 未检测到firewall-cmd，请手动开放8000端口${NC}"
fi

# 12. 创建systemd服务
echo -e "${BLUE}🔧 创建systemd服务...${NC}"
cat > /etc/systemd/system/toutiao-auto-publish.service << EOF
[Unit]
Description=Toutiao Auto Publish Service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${PROJECT_DIR}
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable toutiao-auto-publish

echo -e "${GREEN}"
echo "🎉 环境准备完成！"
echo "=================================="
echo "项目目录: ${PROJECT_DIR}"
echo "访问地址: http://$(curl -s ifconfig.me):8000"
echo "本地访问: http://localhost:8000"
echo "=================================="
echo -e "${NC}"

echo -e "${YELLOW}📋 接下来的步骤:${NC}"
echo "1. 将您的Python代码文件上传到 ${PROJECT_DIR}"
echo "2. 运行: docker-compose build"
echo "3. 运行: docker-compose up -d"
echo "4. 查看日志: docker-compose logs -f"
echo ""
echo -e "${BLUE}💡 Chrome支持说明:${NC}"
echo "✅ 已安装 Google Chrome 浏览器"
echo "✅ 已配置 Xvfb 虚拟显示"
echo "✅ 已安装中文字体支持"
echo "✅ 已优化 DrissionPage 环境"
echo ""
echo -e "${GREEN}✅ 部署脚本执行完成！${NC}"
echo -e "${YELLOW}⚠️ 记得上传您的Python源代码文件到项目目录${NC}"
